package org.zhs.springframework.factory.support;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.NoOp;
import org.zhs.springframework.BeansException;
import org.zhs.springframework.factory.config.BeanDefinition;

import java.lang.reflect.Constructor;

/**
 * Cglib实例化
 */
public class CglibSubclassingInstantiationStrategy implements InstantiationStrategy {

    /**
     * 使用Enhancer创建类
     * @param beanDefinition
     * @param beanName
     * @param ctor
     * @param args
     * @return
     * @throws BeansException
     */
    @Override
    public Object instantiate(BeanDefinition beanDefinition, String beanName, Constructor ctor, Object[] args) throws BeansException {
        //Enhancer是cglib中提供的类，类似于Proxy。传入子类后生成其代理类
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(beanDefinition.getBeanClass());
        // NoOp 表示在钩子函数中不做任何操作
        enhancer.setCallback(new NoOp() {
            @Override
            public int hashCode() {
                return super.hashCode();
            }
        });
        if( null == ctor ){
            return enhancer.create();
        }
        return enhancer.create(ctor.getParameterTypes(), args);
    }

}
